<script setup lang="ts">
import { computed, ref } from "vue";
import Taro, { usePullDownRefresh, useRouter } from "@tarojs/taro";
import { PageContainer } from "@tarojs/components";

import ByIcon from "@/components/ui/ByIcon.vue";
import Qrcode from "@/components/common/Qrcode.vue";
import PopupMerchant from "../components/PopupMerchant.vue";
import CouponEtime from "@/components/common/CouponEtime.vue";
import DetailTicketIntro from "../components/DetailTicketIntro.vue";
import CouponContentItem from "../components/CouponContentItem.vue";

import ApiTicket from "@/api/ticket";
import useFetch from "@/hooks/useFetch";
import useGetUrlLink from "@/hooks/useGetUrlLink";
import setting from "@/utils/setting";

const couponTypeMap = {
  1: "兑换券",
  2: "到店优惠",
  3: "现场优惠",
};

// const couponTypeMap = {
//   0: "兑换券",
//   1: "到店优惠",
//   2: "现场优惠",
// };

const tabActive = ref(0);
const showDetail = ref(false);

const { params } = useRouter();

// H5地址
const [h5Link] = useGetUrlLink({ path: "pages/merchant/index" });

// 购买权益包详情
const { data, refresh } = useFetch<any>(ApiTicket.userTicketDetail, {
  showLoading: true,
  defaultParams: { sn: params.sn },
  afterFetch: (res) => res.detail,
  onFinally() {
    Taro.stopPullDownRefresh();
  },
});

usePullDownRefresh(() => refresh());

const couponList = computed(() => {
  const obj = {
    1: [],
    2: [],
    3: [],
  };

  const { value } = data;

  if (!value) return [];

  value.sku_info.pkg_info.coupon_info.forEach((item) => {
    let key = item.activity_coupon_detail.coupon_type;

    // 兼容旧版本补丁
    key = key === 0 ? 1 : key;

    obj[key].push(item);
  });

  return Object.keys(obj)
    .map((key) => {
      const list = obj[key];

      if (list.length > 0)
        return {
          list,
          key: Number(key),
          label: couponTypeMap[key],
        };

      return undefined;
    })
    .filter((e) => !!e);
});

// 显示商家列表弹窗
const selectedCouponId = ref<number>();

const getDateProps = computed(() => {
  if (data.value) {
    const { act_info, etime_info } = data.value;
    const flag = etime_info.etime_type === 3;

    return {
      start: flag ? act_info.start_time : etime_info.start_time,
      end: flag ? act_info.end_time : etime_info.end_time,
    };
  }
  return { start: "", end: "" };
});

// 是否已用完
const hadUsed = computed(() => {
  const { value } = data;
  return value && value.total_num === value.use_num;
});

// 二维码文本内容
const qrtext = computed(() => {
  const link = h5Link.value;
  const sn = data.value?.sn;

  if (link && sn) {
    return `${link}?cq=${encodeURIComponent(`sn=${sn}`)}`;
  }

  return sn || "";
});
</script>

<template>
  <view class="flex-col h-[calc(100vh-172px)] safe-footer overflow-auto">
    <view class="m-4 rounded-xl overflow-hidden">
      <view class="py-4 text-center bg-primary text-white">
        <view class="">{{ data?.act_info.title }}</view>

        <view class="my-2 text-lg">
          {{ data?.sku_info.pkg_info.package_title }}</view
        >
        <view class="text-sm"
          >有效期：
          <CouponEtime v-bind="getDateProps" />
        </view>
      </view>

      <view class="bg-white py-4 text-dark text-center">
        <view class="relative my-3">
          <Qrcode
            :text="qrtext"
            :width="280"
            :margin="0"
            :darkColor="hadUsed ? '#eee' : '#340F08'"
            class="w-[280px] h-[280px] mx-auto"
          />

          <ByIcon
            v-if="hadUsed"
            class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-10 text-primay"
            name="Used"
            :size="310"
          />
        </view>

        <view
          v-if="setting.env != 'prod'"
          class="my-3 text-center"
          @tap="Taro.setClipboardData({ data: qrtext })"
        >
          点击复制二维码信息
        </view>

        <view class="flex-center">
          <text>{{ data?.sn }}</text>
          <ByIcon
            name="Copy"
            class="ml-1"
            @tap="Taro.setClipboardData({ data: data?.sn })"
          />
        </view>

        <view class="flex-center mt-2">
          <navigator
            class="flex-center"
            :url="`/packageActivity/pages/activity/detail?act_id=${data?.act_id}`"
          >
            <text class="tex-sm underline">查看活动详情</text>
            <ByIcon name="ArrowRight" :size="20" />
          </navigator>
        </view>
      </view>

      <view class="flex justify-between p-3 bg-white">
        <template v-for="(item, index) in couponList" :key="item.key">
          <view
            :class="[
              'text-center text-white px-4 py-2 rounded-md',
              tabActive == index ? 'bg-dark' : 'bg-primary',
            ]"
            @tap="tabActive = index"
          >
            <view>{{ item.label }}</view>
          </view>
        </template>
      </view>

      <view class="bg-[#FFF8EF] border-t-2 border-dotted p-3">
        <CouponContentItem
          v-for="(item, index) in couponList[tabActive]?.list"
          :key="index"
          :source="item"
          @choose="selectedCouponId = $event"
        />
      </view>
    </view>

    <view class="flex-center mt-6 mb-3 text-xs text-dark">
      <text>订单号：{{ data?.order_sn }}</text>
      <ByIcon
        name="Copy"
        class="ml-1"
        @tap="
          Taro.setClipboardData({
            data: `订单:${data?.order_sn};券码：${data?.sn}`,
          })
        "
      />
    </view>
  </view>

  <!-- S 使用说明 -->
  <DetailTicketIntro v-model="showDetail" :act_id="data?.act_id" />
  <!-- E 使用说明 -->

  <page-container
    :show="!!selectedCouponId"
    @afterLeave="selectedCouponId = undefined"
    overlay-style="background:rgba(0,0,0,.5)"
  >
    <PopupMerchant
      v-if="!!selectedCouponId"
      :sn="params.sn!"
      :couponId="selectedCouponId"
      @close="selectedCouponId = undefined"
    />
  </page-container>
</template>

<style lang="less">
page {
  background: linear-gradient(to bottom, #fef7ee, #dec2a0);
}
</style>
